<?php
	require_once(dirname(__FILE__)."/config/include.php");
			
	$time = date("Ymd H:i:s") ;
	
	$_PARA 	= array() ;
	if(array_key_exists('return_code',$_POST))	$_PARA 		= $_POST ;
	else										$_PARA 		= $_GET ;
	ob_start();
	
	$msg = "" ;
	if (array_key_exists('return_code', $_PARA) == false){
		if (!isset($GLOBALS['HTTP_RAW_POST_DATA'])){
		    $xmls = file_get_contents('php://input');
		}else{
			$xmls = $GLOBALS['HTTP_RAW_POST_DATA'] ;
		}
		if (is_null($xmls) || $xmls == ""){
			$xmls = $_POST['json'] ;
		}
		
		if (is_null($xmls)){			
			err_return("没有取到返回数据.") ;		
		}
		$pos = strpos($xmls, 'xml');
	    if (!$pos){
	    	file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","$time -- $xmls.\r\n",FILE_APPEND);	    	
	    	err_return("返回数据非XML.") ;
	    }
	    
	    $msg = "" ;
	    $obj = simplexml_load_string($xmls) ;
	    if(is_object($obj)){
			$obj = get_object_vars($obj);
			foreach($obj as $k=>$tmp){ 
				$_PARA[$k] = strval($tmp) ;
				$msg .= "$k = ".$_PARA[$k]."\r\n" ; 
			}
			file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","$time -- $msg.\r\n",FILE_APPEND);
	    }else{
	    	err_return("XML 解析错误") ;
	    }
	}else{
		$msg = "" ;
		foreach ($_PARA as $k=>$tmp){
			$msg .= "$k = ".$_PARA[$k]."\r\n" ; 
		}
		file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","$time -- $msg.\r\n",FILE_APPEND);
	}
	
	$return_code     = trim($_PARA['return_code']);
	message_log_wx("微信订单回调返回  : $return_code") ;

		
	if ($return_code != "SUCCESS"){
		err_return(trim($_PARA['return_msg'])) ;
	}
	$result_code	= trim($_PARA['result_code']);
	if ($result_code != "SUCCESS"){
		err_return("(".trim($_PARA['err_code']).")".trim($_PARA['err_code_des'])) ;
	}
	
	sql_connect() ;
	
	$out_trade_no  	= trim($_PARA['out_trade_no']);		// 商户订单号	
	$transaction_id = trim($_PARA['transaction_id']);	// 微信支付订单号
	
	
	// 判定订单是否正确
	$log_pay = sql_fetch_one("select * from log_pay_vip where `trade_no` = '$out_trade_no' ") ;
	if (!is_array($log_pay) || !array_key_exists("trade_no", $log_pay)){
		err_return("订单不存在") ;
	}
	if ($out_trade_no != $log_pay['trade_no'])
	{
		err_return("订单号不正确") ;
	}
	$uid = $log_pay['uid'] ;
	// 支付表的 唯一ID
	$prepay_id = $log_pay['prepay_id'] ;
		
	// 验证订单合法性	
	$total_fee = intval($_PARA['total_fee']) ;			// 订单总金额，单位为分
	$cash_fee =  intval($_PARA['cash_fee']) ;			// 现金支付金额
	$openid = trim($_PARA['openid']);					// 用户标识
	$r_data = "微信订单号:$transaction_id , 总金额:$total_fee 分 , 现金支付金额:$cash_fee 分, 支付用户标识:$openid" ;
	$_PARA['MemoText'] = $r_data ;
	$newmemo = json_encode($_PARA,JSON_UNESCAPED_UNICODE);	// json_encode($_PARA) ;

	sql_query("update log_pay_vip set `state` = '1' , `transaction_id` = '$transaction_id' , `memo_xml` = '$newmemo' where `prepay_id` = '$prepay_id' and `state` = 0") ;
	//lwx 设置审核状态
	$log_pay = sql_fetch_one("select * from log_pay_vip where `prepay_id` = '$prepay_id' and `state` = 1") ;
	if (!is_array($log_pay) || !array_key_exists("trade_no", $log_pay)){
		err_return("订单已处理") ;
	}
	
    /*  $vip_level = $log_pay['user_type_class'] ;
	//lwx 新增 根据订单金额设置类别
	//lwx  11.2 付费成功 不修改用户状态  只发短信通知
	// 放在后台审核   sql_query("update user_info set user_type= 3   where id = '$uid'") ;
	 * **/
   sql_query("update log_pay_vip set `state` = '2' , `state_count` = `state_count` + 1 , `endtime` = unix_timestamp() where `prepay_id` = '$prepay_id'") ;
   /* $uinfo = sql_fetch_one("select * from user_info where `id` = '$uid'") ;
	//lwx  新增
	$user_user_type=intval($uinfo['user_type']);
	$user_user_class=intval($uinfo['user_type_class']);
	$tmend = 365 * 24 * 60 * 60 ; // 1年
	
	$sql="select user_id from user_pay_vip where user_id='$uid'";
	$if_exit_payvip=intval(sql_fetch_one_cell($sql));
	//数据不存在 添加数据
	if($if_exit_payvip==0){
	    sql_query("INSERT INTO `user_pay_vip` (`user_id`, `user_type_class`, `start_time`, `end_time`) VALUES ('$uid', '$vip_level', unix_timestamp(), unix_timestamp() + $tmend )  on duplicate key update `start_time` = unix_timestamp() , `end_time` = unix_timestamp() + $tmend") ;
	}else{
	    if ($user_user_class == $vip_level){
	        // 续费
	        if (intval(sql_fetch_one_cell("select `user_type_class` from `user_pay_vip` where `user_id`= '$uid' and `user_type_class` = '$vip_level'")) == $vip_level){
	            // 存在
	            sql_query("update `user_pay_vip` set `end_time` = `end_time` + $tmend where `user_id`= '$uid' and `user_type_class` = '$vip_level'") ;
	        } 
	    } 
	    //user_user_class 1变成5   user_pay_vip start_time为当前时间
	    if($user_user_class==1&&$vip_level==5){
	        $nowtime=time();
	        $end_time=$nowtime+$tmend;
	        sql_query("update `user_pay_vip` set   `start_time` =  $nowtime ,  `end_time`= $end_time ,user_type_class='$vip_level' where `user_id`= '$uid' ") ;
	    }
	    
	    //测试 
	   // sql_query("update `user_pay_vip` set   `start_time` =  $user_user_class ,  `end_time`= $vip_level ,user_pay_vip='$vip_level' where `user_id`= '$uid' ") ;
	    
	}
	sql_query("update `user_info` set `user_type_class` = '$vip_level' where `id` = '$uid'") ;
	//设计师审核通过
	$time=time();
	sql_query("update sys_user_designer set audit_state=1 , audit_uid=1,audit_time='$time' where uid= '$uid'");
	// 付费设计师注册总送积分
    _vip_user_add_score($uid) ; */
    //短信通知财务
    $vip_cw_tel_list=$GLOBALS['VIP_CW_TEL_LIST'];
    send_finance_vip_pay_SMS($uid , $total_fee / 100,$vip_cw_tel_list) ;
	ok_return() ;
	function message_log_wx($message)
	{
		$time = date("Ymd H:i:s") ;
		file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","---------$time ----- $message.\r\n\r\n",FILE_APPEND);
	}
	function err_return($err_message)
	{
		ob_end_clean();
		$show = "<xml>
  					<return_code><![CDATA[FAIL]]></return_code>
  					<return_msg><![CDATA[$err_message]]></return_msg>
				</xml>" ;
	    echo $show ;
		ob_end_flush();
		$time = date("Ymd H:i:s") ;
		file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","$time -- $show.\r\n",FILE_APPEND);
		exit(0) ;
	}
	function ok_return()
	{
		ob_end_clean();
		$show = "<xml>
  					<return_code><![CDATA[SUCCESS]]></return_code>
  					<return_msg><![CDATA[OK]]></return_msg>
				</xml>" ;
	    echo $show ;
		ob_end_flush();
		$time = date("Ymd H:i:s") ;
		file_put_contents(dirname(__FILE__)."/log_pay_wx_vip.txt","$time -- $show.\r\n",FILE_APPEND);
		exit(0) ;
	}
	
?>